import 'package:cms/components/term_items.dart';
import 'package:cms/pages/search/search_cubit.dart';
import 'package:cms/pages/search/search_state.dart';
import 'package:cms/views/list_views/single_list_view.dart';
import 'package:cms/views/list_views/term_list_view.dart';
import 'package:common/export/bloc.dart';
import 'package:common/export/tools.dart';
import 'package:components/keep_alive_wrapper.dart';
import 'package:components/lara_press_app_bar.dart';
import 'package:components/lara_press_box.dart';

import 'package:components/lara_press_input.dart';
import 'package:components/lara_press_tabs.dart';
import 'package:components/lara_press_text.dart';
import 'package:flutter/material.dart';
import 'package:user/state/user_action_history/user_action_history_cubit.dart';
import 'package:user/state/user_action_history/user_action_history_state.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});
  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> with TickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => SearchCubit(tickerProvider: this),
      child: Builder(builder: (context) => _buildPage(context)),
    );
  }

  Widget _buildBody(SearchState state) {
    if (state.isSearch) {
      return Column(
        children: [
          SizedBox(
            height: 30.h,
            child: LaraPressEmptyBox(
              child: LaraPressTabBar(
                controller: state.tabController!,
                tabs: ['文章', '分类'],
                indicator: CustomTabIndicator(
                  color: Theme.of(context).colorScheme.primary,
                  height: 4.0,
                  radius: 2.0,
                  padding: EdgeInsets.symmetric(horizontal: 4.0),
                ),
                labelColor: Theme.of(context).colorScheme.primary,
                unselectedLabelColor: Theme.of(
                  context,
                ).colorScheme.onSurfaceVariant,
              ),
            ),
          ),
          Expanded(
            child: TabBarView(
              controller: state.tabController!,
              children: [
                LaraPressKeepAliveWrapper(
                  page: LaraPressSingleListView(
                    searchKeyword: state.searchKeyword.text,
                  ),
                ),
                LaraPressKeepAliveWrapper(
                  page: LaraPressTermListView(
                    searchKeyword: state.searchKeyword.text,
                  ),
                ),
              ],
            ),
          ),
        ],
      );
    }
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child:
              BlocBuilder<
                LaraPressUserActionHistoryCubit,
                LaraPressUserActionHistoryState
              >(
                builder: (context, state) {
                  if (state.searchHistory.isEmpty) {
                    return SizedBox.shrink();
                  }
                  return ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: .3.sh),
                    child: LaraPressEmptyBox(
                      child: ListView.separated(
                        itemCount: state.searchHistory.length,
                        shrinkWrap: true,
                        padding: EdgeInsets.zero,
                        separatorBuilder: (context, index) {
                          return Divider(
                            color: Theme.of(
                              context,
                            ).colorScheme.surfaceContainerLow,
                            indent: 16,
                            endIndent: 16,
                          );
                        },
                        itemBuilder: (context, index) {
                          return ListTile(
                            visualDensity: VisualDensity.compact,
                            leading: LaraPressIcon(
                              icon: Clarity.history_line,
                              size: 18.sp,
                            ),
                            onTap: () {
                              context.read<SearchCubit>().search(
                                keyword: state.searchHistory[index],
                              );
                            },
                            title: LaraPressText(
                              text: state.searchHistory[index],
                              type: LaraPressTextType.listContent,
                              color: Theme.of(
                                context,
                              ).textTheme.titleMedium!.color,
                              lineHeight: 1,
                            ),
                            trailing: IconButton(
                              onPressed: () {},
                              icon: LaraPressIcon(
                                icon: Clarity.trash_line,
                                color: Theme.of(context).colorScheme.error,
                                size: 18.sp,
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  );
                },
              ),
        ),
        SliverToBoxAdapter(
          child: BlocBuilder<SearchCubit, SearchState>(
            builder: (context, state) {
              return LaraPressBoxConvenience.card(
                margin: EdgeInsets.only(top: 5.h),
                borderRadius: 0,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  spacing: 4.h,
                  children: [
                    LaraPressText(
                      text: "热门分类",
                      type: LaraPressTextType.listTitle,
                      fontWeight: FontWeight.bold,
                    ),
                    ListView.separated(
                      itemCount: state.hotCategory.length,
                      shrinkWrap: true,
                      scrollDirection: Axis.horizontal,
                      separatorBuilder: (context, index) {
                        return SizedBox(width: 5.w);
                      },
                      itemBuilder: (context, index) {
                        return LaraPressTermWithBackground(
                          term: state.hotCategory[index],
                          width: .33.sw,
                          height: .12.sh,
                        );
                      },
                    ).h(.12.sh),
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildPage(BuildContext context) {
    final cubit = BlocProvider.of<SearchCubit>(context);
    return Scaffold(
      appBar: LaraPressAppBar(
        titleSpacing: 0,
        titleWidget: BlocBuilder<SearchCubit, SearchState>(
          builder: (context, state) {
            return Row(
              children: [
                Expanded(
                  child: LaraPressInput(
                    hintText: "请输入搜索关键词",
                    isDense: true,
                    controller: state.searchKeyword,
                  ),
                ),
                IconButton(
                  onPressed: () {
                    cubit.search();
                  },
                  icon: Icon(Icons.search),
                ),
              ],
            );
          },
        ),
      ),
      body: BlocBuilder<SearchCubit, SearchState>(
        builder: (context, state) {
          return _buildBody(state);
        },
      ),
    );
  }
}
